package myJs.user.mission.plot

import myJs.Implicits._
import myJs.Utils._
import myJs.components.{FontArgComponent, FontFamilyComponent}
import myJs.myPkg.LayerOptions
import myJs.myPkg.jquery._
import myJs.tool.Pojo._
import myJs.tool.Tool
import myJs.tool.Tool._
import org.scalajs.dom.ext.Ajax
import org.scalajs.dom.{Element, document}
import scalatags.Text.all._

import org.scalajs.macrotaskexecutor.MacrotaskExecutor.Implicits._
import scala.scalajs.js
import scala.scalajs.js.Date
import scala.scalajs.js.Dynamic.{global => g}
import scala.scalajs.js.JSConverters._
import japgolly.scalajs.react.component.Scala.Unmounted
import myJs.user.FeatureSelectionTool

/**
 * Created by yz on 2019/4/25
 */
object CcaRdaTab {

  val curRPlot = CcaRdaF
  val tabId = curRPlot.name
  var component: Unmounted[Unit, FontArgComponent.State, FontArgComponent.Backend]#Mounted = _

  def init = {
    refreshImage
    refreshConfig()
    registerEvent
  }

  def refreshImage = {
    val url = g.jsRoutes.controllers.MissionToolController.getWorkspaceImage().url.toString
    val fileName = "rdacca.png"
    $(s"#${tabId} img").attr("src",
      s"${url}?missionId=${Tool.getMissionId}&fileName=${fileName}&time=${new Date()}")
  }

  def myRun = {
    val bv = $(s"#${tabId} #form").bv
    bv.validate()
    val valid = bv.isValid()
    if (valid) {
      val element = div(id := "content",
        span(id := "info", messages("running"),
          span(id := "progress", "。。。")), " ",
        img(src := "/assets/images/running2.gif", cls := "runningImage", width := 30, height := 20)
      ).render
      val layerOptions = LayerOptions.title(Tool.zhInfo).closeBtn(0).skin("layui-layer-molv").btn(js.Array())
      val index = layer.alert(element, layerOptions)
      val url = g.jsRoutes.controllers.MissionToolController.plot().url.toString
      val formData = $(s"#${tabId} #form").serialize()
      Ajax.post(url = s"${url}", data = s"${formData}&kind=${CcaRdaF.name}", headers = Map("Content-Type" -> "application/x-www-form-urlencoded")).map { xhr =>
        val rs = xhr.responseText.toJDJAn
        layer.close(index)
        val valid = rs("valid").toB
        if (valid) {
          refreshImage
        } else {
          g.swal("Error", rs.myGet("message"), "error")
        }
      }
    }
  }


  def registerEvent = {
    $(document.body).offThenOn("click", s"#${tabId} .myRun", "", (y: Element) => {
      myRun
    })
    $(document.body).offThenOn("change", s"#${tabId} .myShowSample", "", (y: Element) => {
      showSampleChange(y)
    })
    $(document.body).offThenOn("change", s"#${tabId} .myShowEnv", "", (y: Element) => {
      showEnvChange(y)
    })
    $(document.body).offThenOn("change", s"#${tabId} .myShowSpecies", "", (y: Element) => {
      showSpeciesChange(y)
    })
  }

  def showEnvChange(y: Element) = {
    val myValue = $(y).find(">option:selected").`val`().toString
    component.modState { state =>
      state.copy(envFontShow = myValue == "T")
    }
  }

  def showSampleChange(y: Element) = {
    val myValue = $(y).find(">option:selected").`val`().toString
    component.modState { state =>
      state.copy(sampleFontShow = myValue == "T")
    }
  }

  def showSpeciesChange(y: Element) = {
    val myValue = $(y).find(">option:selected").`val`().toString
    component.modState { state =>
      state.copy(speciesFontShow = myValue == "T")
    }
  }

  def refreshX = {
    val url = g.jsRoutes.controllers.MissionController.getCcaRdaXInfo().url.toString
    Ajax.get(url = s"${url.noCache}&missionId=${Tool.getMissionId}", headers = Map("Content-Type" -> "application/json")).map { xhr =>
      val rs = xhr.responseText.toJArS
      val xHtml = rs.map { x =>
        val id = x.replaceAll("^RDA", "").replaceAll("^CCA", "")
        option(value := s"${id}", s"${x}")
      }.mkString("&nbsp;")
      Tool.getInputByName("x").html(xHtml)
      Tool.getInputByName("y").html(xHtml)
    }
  }

  def refreshFontArg(idStr: String = "") = {
    val fileName = curRPlot.configJsonFileName
    val finalFileName = FeatureSelectionTool.getFinalFileName(idStr, fileName)
    val url = g.jsRoutes.controllers.MissionToolController.getConfigJsonData().url.toString
    Ajax.get(url = s"${url.noCache}&missionId=${Tool.getMissionId}&fileName=${finalFileName}",
      headers = Map("Content-Type" -> "application/json")).map { xhr =>
      val rs = xhr.responseText.toJDJAn
      val data = AllPlotDataTool.getData(rs)
      val state = AllPlotDataTool.getState(data).copy(formJq = $(s"#${tabId} #form")).copy(
        xTitleFontShow = true, xFontShow = true, yTitleFontShow = true, yFontShow = true, mainTitleShow = true,
        mainTitleFontShow = true)
      component.setState(state)
    }
  }

  def refreshConfig(idStr: String = "") = {
    refreshX.map { x =>
      val fileName = curRPlot.configFileName
      val url = g.jsRoutes.controllers.MissionToolController.getConfigData().url.toString
      Ajax.get(url = s"${url.noCache}&missionId=${Tool.getMissionId}&fileName=${fileName}",
        headers = Map("Content-Type" -> "application/json")).map { xhr =>
        val rs = xhr.responseText.toJDJAn.toMyJDS
        Tool.fillByNames(rs, tabId)
        bootStrapValidator
        component = FontArgComponent.Component().renderIntoDOM(document.querySelector(s"#${tabId} #myFontArg"))
        Tool.fillByNameAndTriggers(rs.toJDJAn)
        val c = FontFamilyComponent.Component().renderIntoDOM(document.querySelector(s"#fontFamily"))
        c.setState(FontFamilyComponent.State(rs("fontFamily")))
      }.flatMap { x =>
        Tool.refreshColor(tabId).map { x =>
          refreshFontArg(idStr)
        }
      }

    }
  }

  def bootStrapValidator = {
    val maxNumber = Double.MaxValue
    val basicBVMap = (Tool.getPlotBootstrapValidator.toMap)
    val finalFields = (basicBVMap).toJSDictionary
    val dict: js.Dictionary[js.Any] = js.Dictionary(
      "feedbackIcons" -> js.Dictionary(
        "valid" -> "glyphicon glyphicon-ok",
        "invalid" -> "glyphicon glyphicon-remove",
        "validating" -> "glyphicon glyphicon-refresh",
      ),
      "fields" -> finalFields
    )
    $(s"#${tabId} #form").bootstrapValidator(dict)
  }

}
